<?php
header('Content-Type:text/html;charset=UTF-8');
class  app
{
	//定义模块，默认用INDEX处理。
	 static  $url="index";
	 //定义模块数组
	 static  $act ="index";
	 static function run(){	
		if(!empty($_GET["m"]))
		{
			self::$url=$_GET["m"];
		}
		$module=strtolower(self::$url); 
		$url1=""; 
		if(stripos(self::$url,"_")>-1)
		{
			self::$url=str_replace("__", "/", self::$url);
			$url1=explode("/", self::$url);
			$module=$url1[count($url1)-1];
		}
		if(!in_array($module,$GLOBALS['cfg']['act'])||!file_exists(ROOT."/Action/".self::$url.".class.php"))
		{
			echo "forbidden";die;//提示信息
		}
		if($_GET['action'])
		{
			self::$act=$_GET['action'];
		}
		
		self::init();
	}
	
	private static  function Exception()
	{
		
	}
	private static  function init(){
		
		self::load(ROOT."/libs/Smarty.class.php");
		self::load(ROOT."/include/base.inc.php");
		self::load(ROOT."/Action/".app::$url.".class.php");
		$ControllerClass=app::$url."Controller";
		if(class_exists($ControllerClass))
		{
			
			$Controller = new $ControllerClass();
			if(method_exists($Controller, strtolower(self::$act)))
			{
				$action=self::$act;
				$Controller->$action();
			}
			else{
				die("(-_-):不能操作该方式!");
			}
		}else{
			//没有该控制器
			die("Controller  Error");
		}
	}
	static function load($file)
	{
		@include_once $file; //不确定元素，请加上@ 
	}
	static function rload($file)
	{
		@require_once $file;
	}
	static function checkUserLogin(){
		$refer=SITE_URL;
		$usermsg=explode("|",base64_decode($_SESSION[cookie_auth]));
		if($usermsg[0]>0&&strripos($usermsg[2],"@"))
		{
			return true;
		}else{
			$_SESSION[cookie_auth]=NULL;
		}
		return false;
	}
	static function getUserStatus()
	{
		$usermsg=explode("|",base64_decode($_SESSION[cookie_auth]));
		
		return $usermsg;
	}
	
	/**
	 * 用户退出
	 */
	static function userQuit(){
		session_start();
		$_SESSION[cookie_auth]=NULL;
		return true;
	}
	static function array_del($ada,$data)
	{
		//foreach($data)
	}
	
	/**
	 * 获取时间戳
	 * @param string $Date 处理的时间字符 格式 2010-10-10 12:10:10 or 2010-10-10
	 * @param int $type 添加间隔时间 单位为天。条件不正常的时候。比如说格式不对，根本不是时间
	 * @return int 时间戳
	 */
	static function getTimebyDate($Date,$type=0)
	{
		$temp=explode(" ",$Date);
		
		$temp1=explode("-",$temp[0]);
		
		if(empty($temp1[1]))
		{
			return time();
		}
		$temp2=explode(":",$temp[1]);
		if(empty($temp2[1]))
		{
			return mktime(0,0,0,$temp1[1],$temp1[2],$temp1[0]);
		}
		return mktime($temp2[0],$temp2[1],$temp2[2],$temp1[1],$temp1[2],$temp1[0]);
	}
	/**
	 * 该方式已缓存处理
	 * @param unknown_type $id
	 */
	static function getBugstatus($id)
	{
		app::load(ROOT."/class/bug/bug.class.php");
		app::load(ROOT.'/data/cahce/data_status.php');
		if($status)
		{
			return $status[$id][title];
		}else{
			
			$bug = new bug();
			$status=$bug->getlist("select title,id,type from ".$GLOBALS['cfg']['tablepre']."status ", 1000, 0);
			
			$arry=array();
			foreach($status[data] as $value)
			{
				$arry[$value[id]]=$value;
			}
			
			self::cache_write('status', 'status', $arry);//缓存生成
			
			return $arry[$id][title];
		}
	}
	/**
	 * 获取最新消息
	 * @param int $uid
	 */
	static function getPmCountNews($uid)
	{	
		app::load(ROOT.'/class/users/pm.class.php');
		$pm = new pm();
		$count=$pm->getCountNew($uid); 
		return $count;
	}
	/**
	 * 获取最新需要办理的事务
	 * @param int $uid
	 */
	static  function getAffairsCount($uid)
	{
		app::load(ROOT.'/class/users/pm.class.php');
		$db = new ebase();
		$count=0;
		$count=app::getLogsCount($uid);//
		$count+=app::getWeeksCount($uid);
		$count+=app::getDomsCount($uid);
		$count+=app::getBugCount($uid);
		$count+=app::getDemandCount($uid);
		$count+=app::getFuncCount($uid);
		return intval($count);
	}
	
	/**
	 * 获取待评审日志
	 * @param int $uid
	 */
	static function getLogsCount($uid)
	{
		app::load(ROOT.'/class/users/pm.class.php');
		$db = new ebase();
		$count=$db->db->getCount("select * from ".$GLOBALS['cfg']['tablepre']."work_log where status=0 and auid='$uid' and type='log'");
		return $count;
	}
	/**
	 * 获取待评审周总结
	 * @param int $uid
	 */
	static function getWeeksCount($uid)
	{
		app::load(ROOT.'/class/users/pm.class.php');
		$db = new ebase();
		$count=$db->db->getCount("select * from ".$GLOBALS['cfg']['tablepre']."work_log where status=0 and auid='$uid' and type='week'");
		return $count;
	}
	/**
	 * 获取接收的文档
	 * @param int $uid
	 */
	static function getDomsCount($uid)
	{
		app::load(ROOT.'/class/users/pm.class.php');
		$db = new ebase();
		$count=$db->db->getCount("select * from ".$GLOBALS['cfg']['tablepre']."document_log where status=0 and auid='$uid'");
		return $count;
	}
	/**
	 * 获取bug的待处理
	 * @param int $uid
	 */
	static function getBugCount($uid)
	{
		app::load(ROOT.'/class/users/pm.class.php');
		$db = new ebase();
		$count=$db->db->getCount("select * from ".$GLOBALS['cfg']['tablepre']."bug where statusid<3 and chargeid='$uid'");
		return $count;
	}
	/**
	 * 获取bug的待处理
	 * @param int $uid
	 */
	static function getDemandCount($uid)
	{
		app::load(ROOT.'/class/users/pm.class.php');
		$db = new ebase();
		$count=$db->db->getCount("select * from ".$GLOBALS['cfg']['tablepre']."demand where statusid<3 and chargeid='$uid'");
		return $count;
	}
	/**
	 * 获取bug的待处理
	 * @param int $uid
	 */
	static function getFuncCount($uid)
	{
		app::load(ROOT.'/class/users/pm.class.php');
		$db = new ebase();
		$count=$db->db->getCount("select * from ".$GLOBALS['cfg']['tablepre']."func where statusid<2 and chargeid='$uid'");
		return $count;
	}
	/**
	 * 获取用户头像
	 * @param int $uid
	 * @param string $type
	 * @param bool $fat
	 * @return string html字符串
	 */
	static function getAvatar($uid,$type='small',$fat=false)
	{
		app::load(ROOT.'/class/users/user.class.php');
		$user = new user();
		$header=$user->get_avatar($uid,$type,$fat);
		return $header;
	}
	static function checkAllowModel($allowact){
		//app::load(ROOT."/include/common.inc.php");
		app::load(ROOT."/class/users/user.class.php");
		$user = new user();
		$userSt=$user->checkAllowModel($allowact);//用户权限状态
		switch($userSt)
		{
			case 1:
				return app::foreach_k_v($GLOBALS['cfg']['act']);
			break;
			case 2:
				$error=array();
				if(!in_array($_GET['m'], $GLOBALS['cfg']['normal'])){
					if(!in_array($_GET['action'],array('quit','login','edit','addheader')))
					{
						$error[msg]='对不起，你不够权限访问该模块！';
						$error[refer]=SITE_URL."/?m=main";
						$error[error]=1;
						return $error;
					}
				}
				return app::foreach_k_v($GLOBALS['cfg']['normal']);
				break;
			case 3:
				$error=array();
				if(!in_array($_GET['m'], $GLOBALS['cfg']['senior'])){
					if(!in_array($_GET['action'],array('quit','login','edit','addheader')))
					{
						$error[msg]='对不起，你不够权限访问该模块！';
						$error[refer]=SITE_URL."/?m=main";
						$error[error]=1;
						return $error;
					}
				}
				return app::foreach_k_v($GLOBALS['cfg']['senior']);
				break;
			default:
				if(!in_array($_GET['m'], $userSt))
				{
					
					if(!in_array($_GET['action'],array('quit','login','edit','addheader')))
					{
						$error[msg]='对不起，你没有管理权限！';
						$error[refer]=SITE_URL."/?m=main";
						$error[error]=1;
						return $error;
					}
					
					return $userSt;
				}
				return $userSt;	
				break;
			}
	}
	/**
	 * 对图片的大小进行大小缩放
	 * @param string $fileimg
	 * @param int $width
	 * @param int $height
	 * 
	 * @return string " width=100 " or " height=100 " or "";
	 */
	static  function getImageSizeLimit($fileimg,$width=100,$height=100)
	{
		$lv=$width/$height;
		if(file_exists($fileimg)){
		   $img=getimagesize($fileimg);
		   $oldwidth=$img[0];//原图片高度
		   $oldheight=$img[1];//原图片宽度
		   $limit_w_h='';
		   $bi=$oldwidth/$oldheight;
		   if($bi==$lv)
		   {
		   	 $li=self::setwh($width,$height,$oldwidth,$oldheight);
		   	 if($li){
		
		   	 	$limit_w_h=$li;
		   	 }
		   }
		   elseif($bi<$lv){
		   	 $limit_w_h=" height=$height";
		   	 $li=self::setwh($width,$height,$oldwidth,$oldheight);
		   	 if($li){
		
		   	 	$limit_w_h=$li;
		   	 }
		   }
		   else{
		   	//$limit_w_h=" width=$width";
		   	$li=self::setwh($width,$height,$oldwidth,$oldheight);
		   	if($li){
		
		   	 	$limit_w_h=$li;
		   	 }
		   }
		}
		 return $limit_w_h;
	}
	private function setwh($width,$height,$oldwidth,$oldheight)
	{
		//原图片小于实际图片
      if($width==$height){
      		if($oldwidth>$oldheight)
      		{
      			$limit_w_h=' width='.$width;
      		}
      		else 
      		{
      			$limit_w_h=' height='.$height;
      		}
      }
   	  elseif($width>$oldwidth&&$height>$oldheight)
   	  {
   	  	 $limit_w_h=' width='.$oldwidth;
   	  }elseif($width<$oldwidth&&$height>$oldheight){
   	    $limit_w_h=" width=$width";
   	    if($oldheight>$height)
   	    {
   	    	$limit_w_h=" height=$height";

   	    }
   	  }
       elseif($width>$oldwidth&&$height<$oldheight){
   	    $limit_w_h=" height=$height";

   	  }
    	elseif($width<$oldwidth&&$height<$oldheight){
    		if($oldwidth/$oldheight>1)
    		{
    			 $limit_w_h=" width=$width";
    			 if($oldheight>$height)
		   	    {
		   	    	$limit_w_h=" height=$height";
		
		   	    }
    		}else{
    			 $limit_w_h=" height=$height ";
    		}

   	  }
   	  return $limit_w_h;
	}
	static function foreach_k_v($array){
		$ay=array();
		foreach($array as $value)
		{
			$ay[$value]=$value;
		}
		return $ay;
	}
	static function rules_set_cache()
	{
		app::load(ROOT."/class/ebase.class.php");
		$base =  new ebase();
		$cachelist=$base->db->getAll("select * from ".$GLOBALS['cfg']['tablepre']."rating_rules order by orders");
		
		$cache_array=array();//缓存数组准备
		foreach($cachelist as $value)
		{
			$cache_array[$value[id]]=$value;
		}
		app::cache_write('rules','rules',$cache_array);
	}
	/**
	 * 检测是否存在了
	 * @param float $code 满意系数
	 * @param int $sfid 类型ID
	 */
	static function check_Rules($code,$sfid,$id=0){
		app::load(ROOT."/class/ebase.class.php");
		$base =  new ebase();
		$cachelist=$base->db->getCount("select * from ".$GLOBALS['cfg']['tablepre']."rating_rules where code='$code' and satisfactionid='$sfid' and id<>$id ");
		return $cachelist;
	}
	static function allow_set_cache()
	{
		app::load(ROOT."/class/ebase.class.php");
		$base =  new ebase();
		$allow=$base->db->getAll("select * from ".$GLOBALS['cfg']['tablepre']."permissions where type>0");
		
		$allow_c_array=array();//缓存数组准备
		foreach($allow as $value)
		{
			$allow_c_array[$value[act]]=$value;
		}
		app::cache_write('allowact','allowact',$allow_c_array);
	}
	/**
	 * 缓存生成
	 * @param unknown_type $name 缓存文件名，
	 * @param unknown_type $var	 变量名，	
	 * @param unknown_type $values 需要缓存的数组。
	 */
	static function cache_write($name, $var, $values) {
		
		$cachefile = ROOT.'/data/cache/data_'.$name.'.php';
	
		$cachetext = "<?php\r\n".
			'$'.$var.'='.self::arrayeval($values).
			"\r\n?>";
		if(!self::swritefile($cachefile, $cachetext)) {
			exit("File: $cachefile write error.");
		}
	}
	//写入文件
	static function swritefile($filename, $writetext, $openmod='w') {
		
		//file_put_contents($filename, $writetext);
		//return true;
		if(@$fp = fopen($filename, $openmod)) {
			flock($fp, 2);
			fwrite($fp, $writetext);
			fclose($fp);
			return true;
		} else {
			//runlog('error', "File: $filename write error.");
			return false;
		}
	}
	static function arrayeval($array, $level = 0) {
		
		$space = '';
		for($i = 0; $i <= $level; $i++) {
			$space .= "\t";
		}
		$evaluate = "Array\n$space(\n";
		$comma = $space;
		
		foreach($array as $key => $val) {
			$key = is_string($key) ? '\''.addcslashes($key, '\'\\').'\'' : $key;
			
			$val = !is_array($val) && (!preg_match("/^\-?\d+$/", $val) || strlen($val) > 12 || substr($val, 0, 1)=='0') ? '\''.addcslashes($val, '\'\\').'\'' : $val;
			
			if(is_array($val)) {
				$evaluate .= "$comma$key => ".self::arrayeval($val, $level + 1);
			} else {
				$evaluate .= "$comma$key => $val";
			}
			$comma = ",\n$space";
		}
		$evaluate .= "\n$space)";
		
		return $evaluate;
	}
	/**
	 * 删除所有文件夹下的所有文件
	 * @param string $path
	 * @return 1;
	 */
	static function delDir($path)
	{
	  if (is_dir($path)) 
	  {
	   if ($dh = opendir($path))
	    {
	    while (($file = readdir($dh)) !== false) 
	    {
	     if($file!=".."&&$file!=".")
	     {
	      if(is_dir($path."/".$file))
	      {
	       if(!app::delDir($path."/".$file))
	       {
	       
	          return 0;
	       }
	      }
	      else
	      {
	      	if(!preg_match('/_svn/', $file))
	      	{
	      	 if(!unlink($path."/".$file))
		       {
		        return 0;
		       }
	      	}
	      	return 1;
	      
	      }
	     }
	    }
	    closedir($dh);
	   }
	   return 1;
	  }
	 }
}
/**
 * 权限管理类，包括了模块权限和动作权限。
 * 实现对用户的操作权限的控制，此块为静态类
 * @author Jodendy.com
 *
 */
class Permissions{
	
	
	static function CheckAct($act='',$allowact='')
	{
		return false;
	}
}